package com.ithinks.flow.common.utils.middleware.rabbitMQ;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description RabbitMq连接工具
 * @ClassName ConnectionUtils
 * @Author MR.LI
 * @date 2020.11.26 11:421
 */
public class ConnectionUtils {

    public static final Logger LOGGER = LoggerFactory.getLogger(ConnectionUtils.class);

    public static Connection getConnection(String ip,int port,String vhost,String username,String password){

        LOGGER.info("连接初始化：{}，{}",ip,port);
        Connection connection = null;
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(ip);
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost(vhost);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);

        try {
            connection = connectionFactory.newConnection();
            LOGGER.info("RabbitMQ连接完成：{}，{}",ip,port);
            return connection;
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("获取连接失败：{}",e.getMessage());
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }


    public static void closeConnection(Connection connection){
        try {
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("获取关闭连接失败：{}",e.getMessage());
        }
    }

}
